package api

import (
	"encoding/json"
	"go-iot/app/api/web"
	"go-iot/app/models"
	"go-iot/app/common/mysql"
	"gorm.io/gorm"
	"net/http"
	"time"
	"go-iot/app/common/logger"
)

// 系统配置
func init() {
	var sysConfigResource = Resource{
		Id:   "sys-config",
		Name: "系统配置",
		Action: []ResourceAction{
			QueryAction,
			SaveAction,
		},
	}
	RegResource(sysConfigResource)
	web.RegisterAPI("/system/config", "GET", func(w http.ResponseWriter, r *http.Request) {
		ctl := web.NewController(w, r)
		
		var config models.SystemConfig
		result := mysql.DB.Where("id = ?", "sysconfig").First(&config)
		
		res := map[string]interface{}{}
		if result.Error != nil {
			if result.Error == gorm.ErrRecordNotFound {
				ctl.RespOkData(res)
				return
			}
			ctl.RespError(result.Error)
			return
		}
		
		if len(config.Config) > 0 {
			err := json.Unmarshal([]byte(config.Config), &res)
			if err != nil {
				logger.Errorf("unmarshal config error: %v", err)
			}
		}
		ctl.RespOkData(res)
	})
	
	// 保存配置
	web.RegisterAPI("/system/config/update", "POST", func(w http.ResponseWriter, r *http.Request) {
		ctl := NewAuthController(w, r)
		if ctl.isForbidden(sysConfigResource, SaveAction) {
			return
		}
		
		var ob = struct {
			Id     string                 `json:"id"`
			Config map[string]interface{} `json:"config"`
		}{}
		
		err := ctl.BindJSON(&ob)
		if err != nil {
			ctl.RespError(err)
			return
		}
		
		str, err := json.Marshal(ob.Config)
		if err != nil {
			ctl.RespError(err)
			return
		}
		
		var config models.SystemConfig
		result := mysql.DB.Where("id = ?", ob.Id).First(&config)
		
		if result.Error != nil {
			if result.Error == gorm.ErrRecordNotFound {
				// 创建新配置
				config = models.SystemConfig{
					Id:         ob.Id,
					Config:     string(str),
					CreateTime: time.Now(),
				}
				
				if err := mysql.DB.Create(&config).Error; err != nil {
					ctl.RespError(err)
					return
				}
			} else {
				ctl.RespError(result.Error)
				return
			}
		} else {
			// 更新配置
			if err := mysql.DB.Model(&config).Update("config", string(str)).Error; err != nil {
				ctl.RespError(err)
				return
			}
		}
		
		ctl.RespOk()
	})
	// 系统信息
	web.RegisterAPI("/system/info", "GET", func(w http.ResponseWriter, r *http.Request) {
		ctl := NewAuthController(w, r)
		m := map[string]string{}
		m["release"] = ""
		ctl.RespOkData(m)
	})

	// 更新token过期时间
	web.RegisterAPI("/token/refresh", "GET", func(w http.ResponseWriter, r *http.Request) {
		ctl := NewAuthController(w, r)
		ctl.RespOk()
	})
}
